
def get_pre_prompt(pre_prompt_name) -> str:
    '''
    读取预设的prompt, 用于生成问题
    :param pre_prompt_name: str, 预设的prompt的文件名, 不包含后缀
    :return: str, 预设的prompt
    '''
    pre_prompt = ""
    with open(f"data/{pre_prompt_name}.txt", "r", encoding="utf8") as f:
        pre_prompt = f.read()
    return pre_prompt

def get_replace() -> dict:
    '''
    读取替换的内容, 用于生成问题
    :return: dict, 替换的内容, key为替换的内容, value为替换的内容的列表  
    '''
    replace = {}
    with open("data/replace.txt", "r", encoding="utf8") as f:
        replace_key = ""
        for line in f:
            line = line.strip()
            if not line:
                continue
            if line.startswith("[") and line.endswith("]"):
                replace_key = line[1:-1]
                continue
            replace[replace_key] = replace.get(replace_key, []) + [line]
    return replace

def get_questions(filename: str="questions"):
    '''
    读取问题, 用于生成问题
    :return: list, 问题列表, 示例：["1. 问题", "2. 问题", ...]
    '''
    questions = []
    with open(f"data/{filename}.txt", "r", encoding="utf8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            questions.append(line)
    return questions

def replace_func(pre_prompt: str, replace_dict: dict) -> dict:
    '''
    替换pre_prompt中的内容
    :param pre_prompt: str, 预设的prompt
    :param replace_dict: dict, 替换的内容, key为替换的内容, value为替换的内容的列表
    :return: dict, 替换后的prompt字典
    '''
    raw_prompts = [("", pre_prompt)]
    for replace_key, replace_list in replace_dict.items():
        new_prompts = []
        for i in range(len(raw_prompts)):
            prompt = raw_prompts[i]
            for replace_str in replace_list:
                new_prompt_key = \
                    f"{prompt[0]}{"_" if len(prompt[0]) > 0 else ""}{replace_key}+{replace_str if len(replace_str) < 19 else hash(replace_str)}"
                new_prompt = prompt[1].replace("{%s}" % replace_key, replace_str)
                new_prompts.append((new_prompt_key, new_prompt))
        raw_prompts = new_prompts
    
    return {key: value for key, value in raw_prompts}